var Common = {
    moveArrs:[[0,-1],[1,0],[0,1],[-1,0]],
    judgeArrs:[[0,1],[-1,0],[0,-1],[1,0]],
    notMoves:[[],[],[],[1,5,9,13]],
    moveClass:["moveTop","moveRight","moveBottom","moveLeft"],
    inClass:["moveBottom","moveLeft","moveTop","moveRight"],
	idPreg:/^#[\w\.]+$/,
    zoomQueue:[],


	f:function(selector,elems){
		if(Common.idPreg.test(selector)){
			return document.getElementById(selector.substr(1));
		}else{
			if(selector.indexOf(".")===-1){
				return document.getElementsByTagName(selector);
			}else{
				var arrs = selector.split(" ");
				var es = [];
				if(arrs.length === 1){
					es = document.getElementsByTagName(arrs[0]);
					return es;
				}else{
					es = document.getElementsByTagName(arrs[0]);
					var className = arrs[1].substr(1);
					var newEs = [];
					for(var i=0;i<es.length;i++){
						var item = es[i];
						var itemClassName = item.className;
						if(itemClassName&&itemClassName.indexOf(className)!==-1){
							newEs.push(item);
						}
					}
					return newEs;
				}
			}
		}
	},
	addEventListener:function(target,eType,callback){
		target.addEventListener(eType,callback);
	},
	doMove:function(dir){
        var ccc = [[0,0,1,1],[3,3,-1,-1],[3,3,-1,-1],[0,0,1,1]];
        var cc = ccc[dir];
        var x = 0,y=0;
        var notMove = Common.notMoves[dir];
        for(y=cc[0];Common.isXYInRule(x,y);y+=cc[2]){
            for(x=cc[1];Common.isXYInRule(x,y);x+=cc[3]){
                    var idx = Common.xyToIndex(x,y);
                    var item = Common.f("#box"+idx);
                    var itemValue = Common.conStrToValue(item.getAttribute("data-box-value"));
                    var moveLock = item.getAttribute("data-box-move-lock");
                    if(itemValue!==0&&moveLock!==1){
                        Common.moveItem(dir,item);
                    }
            }
            x = 0;
        }
        Common.newItem(2);
	},
    /**
     * 移动item，如果往左滑可以看作是向左边移动
     * @param dir
     * @param item
     */
	moveItem:function(dir,item){
        var move = Common.moveArrs[dir];
        var curIndex = item.getAttribute("data-box-index");
        var curValue = Common.conStrToValue(item.getAttribute('data-box-value'));
        var curXY = Common.indexToXY(curIndex);
        var mergeLock = parseInt(item.getAttribute("data-box-merge-lock"));
        var mergeItem = false;
        if(curXY){
            var flag = true;
            var moveIdx = -1;
            var mergeRes = Common.judgeMerge(dir,item);
            if(mergeRes!==false){
                var idx = mergeRes.idx;
                var tItem = Common.f("#box"+idx);
                tItem.setAttribute("data-box-move-lock",1);//不参与到移动计算中了
                item.setAttribute("data-box-merge-lock",1);//这一轮不能和其他的再进行合并了
                mergeItem = tItem;
                moveIdx = curIndex;
            }
            for(var ax=curXY.x+move[0],ay=curXY.y+move[1];Common.isXYInRule(ax,ay);){
                var idx = Common.xyToIndex(ax,ay);
                var useitem = Common.f("#box"+idx);
                if(useitem) {
                    var itemValue = Common.conStrToValue(useitem.getAttribute("data-box-value"));
                    console.log(useitem,item);
                    if(itemValue!==0){
                        var preIdx = Common.xyToIndex(ax+(move[0]*-1),ay+(move[1]*-1));
                        //如果和现在的idx不相同的话，转移这个当前这个对象到那个上去
                        if(preIdx!==curIndex){
                            moveIdx = preIdx;
                            break;
                        }else{
                            flag = false;
                        }
                    }else{
                        moveIdx = idx;
                    }
                }
                ax+=move[0];
                ay+=move[1];
            }
            if(flag===true&&moveIdx>=0){
                var targetItem = Common.f("#box"+moveIdx);
                Common.moveToItem(item,targetItem,mergeItem);
            }
        }
	},
    judgeMerge:function(dir,item){
        var move = Common.judgeArrs[dir];
        var curValue = Common.conStrToValue(item.getAttribute("data-box-value"));
        var curIndex = item.getAttribute("data-box-index");
        var curXY = Common.indexToXY(curIndex);//当前的xy映射
        if(curXY) {
            var startX = curXY.x;
            var startY = curXY.y;
            for(var ax=startX+ move[0],ay=startY +move[1];Common.isXYInRule(ax,ay);) {
                var idx = Common.xyToIndex(ax,ay);
                var useitem = Common.f("#box"+idx);
                if(useitem) {
                    var itemValue = Common.conStrToValue(useitem.getAttribute("data-box-value"));
                    if(itemValue!==0) {
                        if(itemValue===curValue){
                           return {"idx":idx};
                        }else{
                            break;
                        }
                    }
                }
                ax+=move[0];
                ay+=move[1];
            }
        }
        return false;
    },
    isXYInRule:function(x,y){
        if(x>=0&&x<4&&y>=0&&y<4){
               return true;
        }
    },
    conStrToValue:function(str){
        return str===null?0:parseInt(str);
    },
    /**
     * x,y转换为索引
     * @param x
     * @param y
     * @returns {*}
     */
    xyToIndex:function(x,y){
        return y*4+x+1;
    },
    /**
     * 索引转换成x,y
     * @param idx
     * @returns {{x: number, y: number}}
     */
    indexToXY:function(idx){
        var xA = (idx%4)-1;
        var yA = Math.floor(idx/4);
        if(xA<0){
            xA = 3;
        }
        if(xA===3){
            yA--;
        }
        return {"y":yA,"x":xA};
    },
	gameInit:function(dir){

		var boxes = Common.f("div .box");
		for(var i in boxes){
			var item = boxes[i];
			var num = parseInt(i)+1;
			var xy = Common.indexToXY(num);
            var left = 20*(xy.x)+(xy.x+1)*4+"%";
            var top = 20*(xy.y)+(xy.y+1)*4+"%";
            item.setAttribute("data-box-index",num);
			item.setAttribute('id',"box"+num);
            Common.addStyle(item,{"left":left,"top":top});
		}
        var backs = Common.f("div .backBox");
        for(var i in backs){
            var item = backs[i];
            var num = parseInt(i)+1;
            var xy = Common.indexToXY(num);
            var left = 20*(xy.x)+(xy.x+1)*4+"%";
            var top = 20*(xy.y)+(xy.y+1)*4+"%";
            item.setAttribute("data-box-index",num);
            Common.addStyle(item,{"left":left,"top":top});
        }
        Common.newItem(4);
        Common.newItem(2);
	},
	in_array:function(search,arrs){
		for(var i in arrs){
			if(arrs[i]==search){
				return true;
			}
		}
		return false;
	},
	mergeClass:function(ele,inClassName,dir){
		if(ele){
			var className = ele.className;
			if(!className){
				className = "";
			}
			if(dir==1){
				if(className.indexOf(inClassName)===-1){
					className += " "+inClassName;
				}
			}else if(dir==2){
				var idx  = className.indexOf(inClassName);
				if(idx!==-1){
					var newClass = className.substr(0,idx)+className.substr(idx+inClassName.length);
					className = newClass;
				}
			}
			ele.className = className;
		}
	},
    moveToItem:function(fromItem,toItem,mergeItem) {
        var tempNode = fromItem.cloneNode(true);
        tempNode.setAttribute('id', "tempNode");
        tempNode.style.zIndex = 3;
        Common.f("#inMoveWrapper").appendChild(tempNode);

        function innfc(tempNode,toItem,fromItem) {
            if(tempNode.getAttribute("data-box-index")===toItem.getAttribute("data-box-index")){
                var newValue = Common.conStrToValue(tempNode.getAttribute("data-box-value"));
                var tBeforeValue = toItem.getAttribute("data-box-value");
                Common.changeItem(toItem,tBeforeValue,newValue);
                Common.f("#inMoveWrapper").removeChild(Common.f("#tempNode"));//展示完效果就删掉
                return ;
            }
            var toStyle = toItem.style;
            var newStyle = {"left": toStyle.left, "top": toStyle.top};
            tempNode.style.webkitTransitionDuration = "500.0ms";//设置持续时间500ms
            Common.clearItem(fromItem);
            toItem.setAttribute("data-box-value", tempNode.getAttribute("data-box-value"));//设置目的地的value，防止被再次合并
            setTimeout((function (node, newStyle,f) {
                return function () {
                    Common.addStyle(node, newStyle);
                }
            })(tempNode, newStyle,fromItem), 20);
            setTimeout((function (tempNode, tItem,fItem) {
                return function () {
                    var newValue = Common.conStrToValue(tempNode.getAttribute("data-box-value"));
                    var tBeforeValue = tItem.getAttribute("data-box-value");
                    Common.mergeClass(tItem, "num" + tBeforeValue, 2);//删除原来的色类
                    Common.mergeClass(tItem, "num" + newValue, 1);//增加新的色类
                    fItem.setAttribute("data-box-value","0");
                    tItem.innerText = newValue;
                    setTimeout((function (node) {
                        return function () {
                            Common.f("#inMoveWrapper").removeChild(Common.f("#tempNode"));//展示完效果就删掉
                            setTimeout((function (node, newStyle) {
                                return function () {
                                    Common.addStyle(node, newStyle);
                                }
                            })(tempNode, newStyle), 20);
                        }
                    })(tempNode), 500);
                }
            })(tempNode, toItem,fromItem), 500);
        }
        if (mergeItem) {
            var tempMergeItem = mergeItem.cloneNode(true);
            tempMergeItem.setAttribute('id', "mergeTemp");
            tempMergeItem.style.zIndex = 3;
            Common.f("#inMoveWrapper").appendChild(tempMergeItem);
            Common.clearItem(mergeItem,tempNode.getAttribute("data-box-value"));
            mergeItem.style.webkitTransitionDuration = "100.0ms";//设置持续时间100ms
            var mergeStyle = {"left":tempNode.style.left,"top":tempNode.style.top};
            Common.clearItem(fromItem);//晴空掉原来的fromItem
            console.log(tempNode.getAttribute("data-box-value"));
            toItem.setAttribute("data-box-value", tempNode.getAttribute("data-box-value"));//设置目的地的value，防止被再次合并
            setTimeout((function (node, newStyle) {
                return function () {
                    Common.addStyle(node, newStyle);
                }
            })(tempMergeItem, mergeStyle), 20);
            setTimeout((function (node, mItem,toItem,fromItem) {
                return function () {
                    var orgValue = Common.conStrToValue(node.getAttribute("data-box-value"));
                    var newValue = orgValue*2;
                    Common.clearItem(mItem,orgValue);
                    Common.changeItem(node,orgValue,newValue);
                    innfc(node,toItem,fromItem);
                    Common.f("#inMoveWrapper").removeChild(mItem);
                }
            })(tempNode, tempMergeItem,toItem,fromItem), 120);
            setTimeout((function(toItem){
                return function(){
                    Common.zoomAnimateFunc(toItem)();
                }
            })(toItem),600);
        }else{
            innfc(tempNode,toItem,fromItem);
        }

    },
    changeItem:function(item,orgValue,newValue){
        item.innerText = newValue;
        Common.mergeClass(item, "num" + orgValue, 2);//移除原来的色类
        Common.mergeClass(item, "num" + newValue, 1);//增加新的色类
        item.setAttribute("data-box-value",newValue);
    },
    clearItem:function(item,val) {
        var orgValue = item.getAttribute("data-box-value");
        if(val){
            orgValue = val;
        }
        item.setAttribute("data-box-value",0);
        Common.mergeClass(item,"num"+orgValue,2);//删除原来的类
        item.innerText = "";
    },
    zoomAnimateFunc:function(ele) {
        return function () {
            Common.mergeClass(ele, 'itemLarge', 1);
            setTimeout((function (obj) {
                return function(){
                    Common.mergeClass(obj, "itemLarge", 2)
                }
            })(ele), 200);
        }
    },
    addStyle:function(ele,styleObj) {
        var style = ele.style;
        for(var key in styleObj){
            var value = styleObj[key];
            style[key] = value;
        }
    },
    newItem:function(value) {
        var freeBoxes = [];
        var random = Math.floor(Math.random()*15+1);
        for(var i=1;i<=16;i++){
            var box = Common.f("#box"+i);
            var v = Common.conStrToValue(box.getAttribute("data-box-value"));
            if(v === 0){
                freeBoxes.push(box);
            }
        }
        var len = freeBoxes.length;
        if(len > 0){
            var random = Math.floor(Math.random()*len);
            var box = freeBoxes[random];
            Common.mergeClass(box,'itemSmall',1);
            Common.changeItem(box,0,value);
            setTimeout((function(box){
                return function(){
                    Common.mergeClass(box,'itemSmall',2);
                }
            })(box),20);

        }
    },
    initListener:function(){
    }
}
Common.gameInit();